{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter containing:\n",
      "tensor([[ 0.4318, -0.4256]], requires_grad=True)\n",
      "Parameter containing:\n",
      "tensor([0.6730], requires_grad=True)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor([[0.6730],\n",
       "        [1.1048],\n",
       "        [0.2473],\n",
       "        [0.6792]], grad_fn=<AddmmBackward>)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#训练数据,线性回归\n",
    "torch.random.manual_seed(420) #人为设置随机数种子\n",
    "X = torch.tensor([[0,0],[1,0],[0,1],[1,1]], dtype = torch.float32)\n",
    "#单层神经网络，由于训练数据有两个特征，所以2个输入,预测值为单个数据,1个输出\n",
    "output = torch.nn.Linear(2,1)\n",
    "print(output.weight)  #随机生成权重w和截距b,Linear(2,1,bias=False)则不会生成b\n",
    "print(output.bias)\n",
    "zhat = output(X) #zhat为预测值\n",
    "zhat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[0.6622],\n",
      "        [0.7512],\n",
      "        [0.5615],\n",
      "        [0.6636]], grad_fn=<SigmoidBackward>)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[1, 1, 1, 1]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#二分类神经网络\n",
    "X = torch.tensor([[0,0],[1,0],[0,1],[1,1]], dtype = torch.float32)\n",
    "torch.random.manual_seed(420) #人为设置随机数种子\n",
    "dense = torch.nn.Linear(2, 1)\n",
    "zhat = dense(X)\n",
    "sigma = torch.sigmoid(zhat)\n",
    "print(sigma)\n",
    "y = [int(x) for x in sigma > 0.5]\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "#深度神经网络\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.random.manual_seed(420) #人为设置随机数种子\n",
    "X = torch.rand((500, 20), dtype = torch.float32)\n",
    "y = torch.randint(low=0, high=3, size=(500,1), dtype=torch.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "#假设我们有500条数据，20个特征，标签为3分类。我们现在要实现一个三层神经网络，这个神经网络的\n",
    "#架构如下：第一层有13个神经元，第二层有8个神经元，第三层是输出层。其中，第一层的激活函数是\n",
    "#relu，第二层是sigmoid。我们要如何实现它呢？来看代码：\n",
    "class Model(nn.Module):\n",
    "    def __init__(self, in_features=10, out_features=2):\n",
    "        super(Model, self).__init__()\n",
    "        #定义模型\n",
    "        self.liner1 = nn.Linear(in_features, 13, bias=True)\n",
    "        self.liner2 = nn.Linear(13, 8, bias=True)\n",
    "        self.output = nn.Linear(8, out_features, bias=True)\n",
    "        \n",
    "    def forward(self, x):\n",
    "        #输入数据,向前传播\n",
    "        z1 = self.liner1(x)\n",
    "        sigma1 = torch.relu(z1)\n",
    "        z2 = self.liner2(sigma1)\n",
    "        sigma2 = torch.sigmoid(z2)\n",
    "        z3 = self.output(sigma2)\n",
    "        sigma3 = torch.softmax(z3, dim=1)\n",
    "        return sigma3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0., 1., 2.])"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y.unique() #查看标签有多少分类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_ = X.shape[1]\n",
    "output_ = len(y.unique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.4140, 0.3496, 0.2365],\n",
       "        [0.4210, 0.3454, 0.2336],\n",
       "        [0.4011, 0.3635, 0.2355],\n",
       "        ...,\n",
       "        [0.4196, 0.3452, 0.2352],\n",
       "        [0.4153, 0.3455, 0.2392],\n",
       "        [0.4153, 0.3442, 0.2405]], grad_fn=<SoftmaxBackward>)"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "torch.random.manual_seed(420) #人为设置随机数种子\n",
    "net = Model(in_features=input_, out_features=output_)\n",
    "net.forward(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "torch.Size([13, 20])"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net.liner1.weight.shape"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
